package com.carrental.auth.controller;

import com.carrental.auth.dto.LoginDTO;
import com.carrental.auth.dto.RegisterDTO;
import com.carrental.auth.service.UserService;
import com.carrental.auth.vo.LoginVO;
import com.carrental.auth.vo.UserInfoVO;
import com.carrental.common.response.Result;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);
    
    private final UserService userService;

    /**
     * 用户登录
     *
     * @param loginDTO 登录参数
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody @Valid LoginDTO loginDTO) {
        log.info("接收到登录请求: username={}", loginDTO.getUsername());
        try {
            LoginVO loginVO = userService.login(loginDTO);
            log.info("用户登录成功: username={}", loginDTO.getUsername());
            return Result.success(loginVO);
        } catch (Exception e) {
            log.error("用户登录失败: username={}, 错误信息: {}", loginDTO.getUsername(), e.getMessage());
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 用户注册
     *
     * @param registerDTO 注册参数
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody @Valid RegisterDTO registerDTO) {
        log.info("接收到注册请求: username={}, mobile={}", registerDTO.getUsername(), registerDTO.getMobile());
        try {
            boolean result = userService.register(registerDTO);
            if (result) {
                log.info("用户注册成功: username={}", registerDTO.getUsername());
            } else {
                log.warn("用户注册失败: username={}", registerDTO.getUsername());
            }
            return Result.success(result);
        } catch (Exception e) {
            log.error("用户注册失败: username={}, 错误信息: {}", registerDTO.getUsername(), e.getMessage());
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     *
     * @param request 请求
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfo(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        String clientIp = getClientIp(request);
        log.info("接收到获取用户信息请求: IP={}", clientIp);
        
        if (token == null) {
            log.warn("获取用户信息失败: 未提供token, IP={}", clientIp);
            return Result.unauthorized();
        }
        
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        // 从token中获取用户ID
        Long userId = userService.getUserIdFromToken(token);
        if (userId == null) {
            log.warn("获取用户信息失败: 无效的token, IP={}", clientIp);
            return Result.unauthorized();
        }
        
        try {
            UserInfoVO userInfoVO = userService.getUserInfo(userId);
            log.info("获取用户信息成功: userId={}, IP={}", userId, clientIp);
            return Result.success(userInfoVO);
        } catch (Exception e) {
            log.error("获取用户信息失败: userId={}, IP={}, 错误信息: {}", userId, clientIp, e.getMessage());
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 刷新token
     *
     * @param request 请求
     * @return 新token
     */
    @PostMapping("/refresh")
    public Result<String> refreshToken(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        String clientIp = getClientIp(request);
        log.info("接收到刷新token请求: IP={}", clientIp);
        
        if (token == null) {
            log.warn("刷新token失败: 未提供token, IP={}", clientIp);
            return Result.unauthorized();
        }
        
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String refreshedToken = userService.refreshToken(token);
        if (refreshedToken == null) {
            log.warn("刷新token失败: 无效的token, IP={}", clientIp);
            return Result.unauthorized();
        }
        
        log.info("刷新token成功: IP={}", clientIp);
        return Result.success(refreshedToken);
    }

    /**
     * 退出登录
     *
     * @param request 请求
     * @return 退出结果
     */
    @PostMapping("/logout")
    public Result<Boolean> logout(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        String clientIp = getClientIp(request);
        log.info("接收到退出登录请求: IP={}", clientIp);
        
        if (token == null) {
            log.warn("退出登录失败: 未提供token, IP={}", clientIp);
            return Result.unauthorized();
        }
        
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        boolean result = userService.logout(token);
        if (result) {
            log.info("退出登录成功: IP={}", clientIp);
        } else {
            log.warn("退出登录失败: 无效的token, IP={}", clientIp);
        }
        
        return Result.success(result);
    }
    
    /**
     * 获取客户端IP地址
     * 
     * @param request HTTP请求
     * @return IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * 用户登录
     *
     * @param password 登录参数
     * @return 登录结果
     */
    @GetMapping("/test/password")
    public Result<String> testPassword(@RequestParam String password) {
        try {
            String pd = userService.testPassword(password);
            return Result.success(pd);
        } catch (Exception e) {

            return Result.failed(e.getMessage());
        }
    }

} 